import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

const About = () => import(/* webpackChunkName: "about" */ '../views/About.vue')
const BookDetail = () => import(/* webpackChunkName: "BookDetail" */ '../views/BookDetail.vue')
const Book = () => import(/* webpackChunkName: "Book" */ '../views/Book.vue')
const Game = () => import(/* webpackChunkName: "Game" */ '../views/Game.vue')
const Notfound = () => import(/* webpackChunkName: "Notfound" */ '../views/Notfound.vue')
const Login = () => import(/* webpackChunkName: "Login" */ '../views/Login.vue')
const Server = () => import(/* webpackChunkName: "Server" */ '../components/Server.vue')
const Product = () => import(/* webpackChunkName: "Product" */ '../components/Product.vue')


//  /book/3

// import About from '../views/About.vue'

Vue.use(VueRouter)  // vue的插件 把vuerouter当做插件引入

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta:{
      requiresAuth: true,
      isHidden: true
    },
    children: [
      {
        path: 'server',
        name: 'Server',
        component: Server
      },
      {
        path: 'product',
        name: 'Product',
        component: Product
      },
    ]
  },
  {
    path: '/bookdetail/:bid',
    name: 'BookDetail',
    component: BookDetail,
    props: true,
    meta:{
      isHidden: true
    },
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta:{
      isHidden: true
    },
    beforeEnter: (to, from, next) => {
      // ...
      // 只有在进入 login时候执行
      console.log('进入login路由');
      localStorage.removeItem('token');
      next()
    }
  },
  {
    path: '/book',
    name: 'Book',
    component: Book,
    meta:{
      requiresAuth: true
    }
  },
  {
    path: '/game',
    name: 'youxi',
    component: Game
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: About
    // component: About
  },
  {
    // 会匹配所有路径
    path: '*',
    name: '404',
    component: Notfound,
    meta:{
      isHidden: true
    },
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由实例化以后 
// 全局路由守卫 
router.beforeEach((to, from, next) => {
  // ...
  console.log('准备跳转');
  // 在这里做权限验证
  if (to.name == 'Login') {
    console.log('准备进入login路由');
    next();
  } else {
    if(to.meta.requiresAuth){
      console.log(to.name);
      const token = localStorage.getItem('token');
      if (token) {
        next();
      } else {
        next({
          name: 'Login'
        })
      }
    }else{
      next();
    }

  }


})

// 全局后置

router.afterEach((to, from) => {
  // ...
  // 路由解析完成
})

export default router
